//
//  AutoScrollInputViewController.m
//  YoucApp
//
//  Created by Liam on 11/20/12.
//
//

#import "AutoScrollInputViewController.h"

@interface AutoScrollInputViewController ()

@property (nonatomic, retain) NSMutableArray *textFieldArray;
@property (nonatomic, retain) UIScrollView *scrollView;

@end

@implementation AutoScrollInputViewController

@synthesize scrollView = _scrollView;
@synthesize textFieldArray = _textFieldArray;
@synthesize contentView = _contentView;

// Call this method somewhere in your view controller setup code.

- (void)registerForKeyboardNotifications
{
    [[NSNotificationCenter defaultCenter] addObserver:self
											 selector:@selector(keyboardWasShown:)
												 name:UIKeyboardDidShowNotification object:nil];
	
    [[NSNotificationCenter defaultCenter] addObserver:self
											 selector:@selector(keyboardWasHidden:)
												 name:UIKeyboardDidHideNotification object:nil];
}

- (void)removeForKeyboardNotifications
{
	[[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (UIView *)findInputFirstResponder:(UIView *)view
{
	UIView *retView = nil;
	
    if (view.isFirstResponder) {
        retView = view;
    }
	if (!retView)
	{
		for (UIView *subView in view.subviews)
		{
			retView = [self findInputFirstResponder:subView];
			if (retView)
				break;
		}
	}
    return retView;
}

// Called when the UIKeyboardDidShowNotification is sent.

- (void)keyboardWasShown:(NSNotification*)aNotification
{
	if (keyboardShown) {
        return;
    }
	if (self.scrollView)
	{
		NSDictionary * info = [aNotification userInfo];
		NSValue *avalue = [info objectForKey:UIKeyboardFrameEndUserInfoKey];
		CGRect keyboardRect = [self.view convertRect:[avalue CGRectValue] fromView:nil];
		CGRect viewFrame = [self.scrollView frame];
		viewFrame.size.height -= keyboardRect.size.height;
		self.scrollView.frame = viewFrame;
		
		UIView * activeField = [self findInputFirstResponder:self.view];
		
		CGRect textFieldRect = [activeField frame];
		[self.scrollView scrollRectToVisible:textFieldRect animated:YES];
		keyboardShown = YES;
	}
}

// Called when the UIKeyboardDidHideNotification is sent

- (void)keyboardWasHidden:(NSNotification*)aNotification
{
	if (self.scrollView)
	{
		NSDictionary* info = [aNotification userInfo];

		// Get the size of the keyboard.
		NSValue * value = [info objectForKey:UIKeyboardFrameBeginUserInfoKey];
		CGSize keyboardSize = [value CGRectValue].size;

		// Reset the height of the scroll view to its original value
		CGRect viewFrame = [self.scrollView frame];
		viewFrame.size.height += keyboardSize.height;
		self.scrollView.frame = viewFrame;

		keyboardShown = NO;
	}
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)dealloc
{
	SAFE_RELEASE(_scrollView);
	SAFE_RELEASE(_textFieldArray);
	SAFE_RELEASE(_contentView);
	
	[super dealloc];
}

- (void)viewDidUnload {
	self.scrollView = nil;
	self.textFieldArray = nil;
	self.contentView = nil;
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
	
	keyboardShown = NO;
	self.scrollView = (UIScrollView *)self.view;
	[self.scrollView setContentSize:self.contentView.frame.size];
//	self.scrollView.delaysContentTouches = NO;
//	self.scrollView.canCancelContentTouches = YES;
	
	self.textFieldArray = [NSMutableArray array];
	
	for (UITextField *textField in self.contentView.subviews)
	{
		if ([textField isKindOfClass:[UITextField class]])
		{
			textField.delegate = self;
			[self.textFieldArray addObject:textField];
		}
	}
}

- (void)viewWillAppear:(BOOL)animated
{
	[self registerForKeyboardNotifications];
	
	[super viewWillAppear:animated];	
}

- (void)viewWillDisappear:(BOOL)animated
{
    [self removeForKeyboardNotifications];
    [super viewWillDisappear:animated];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)inputDone
{
	
}

#pragma mark UITextFieldDelegate

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
	NSUInteger index = [self.textFieldArray indexOfObject:textField];
	if (index == [self.textFieldArray count] - 1)
	{
		[self inputDone];
	}
	else
	{
		UITextField * nextTextField = [self.textFieldArray objectAtIndex:index+1];
		[nextTextField becomeFirstResponder];
	}
	
	return YES;
}

@end
